const express = require('express')
const uploader=require('express-fileupload')
const { appendFile,writeFile ,existsSync}= require('fs')
const { resolve, extname } = require('path')
const app = express()
const port = 3000
app.use('/',express.static('public'))
app.use(express.json())
app.use(express.urlencoded({
    urlencoded:true,
    // extended:false
}))
app.use(uploader())

app.post('/updata', async (req, res) => {
    const {file}=req.files
    const {name,type,indexSize,hash}=req.body

    const fname=extname(name)
    const fileName= resolve(__dirname,`./public/${hash}${fname}`)
    if(+indexSize){
        if(!existsSync(fileName)){
            
            res.status(400)
            .send({message:"文件不存在!!"})
            return
        }
        
        await   appendFile(fileName,file.data,(error)=>{})
        res.send({message:"append"})
        return
    }else{

        await   writeFile(fileName,file.data,(error)=>{})
        res.send({message:file})
    }
    console.log('file----------------',indexSize);
  


})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})